const { app, BrowserWindow } = require('electron');
const path = require('path');
const { spawn } = require('child_process');

let serverProcess;

function createWindow() {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false
        }
    });

    win.loadFile(path.join(__dirname, 'index.html')).catch(err => {
        console.error('Failed to load index.html:', err);
        app.quit();
    });

    win.on('closed', () => {
        if (serverProcess) {
            serverProcess.kill();
        }
    });
}

app.on('ready', () => {
    console.log('App is ready');

    // Correctly handle the path to server.js after packaging
    const serverPath = path.join(__dirname, 'server.js');
    const nodePath = path.join(process.resourcesPath, 'resources', 'node.exe');

    serverProcess = spawn(nodePath, [serverPath], {
        stdio: 'inherit'
    });

    serverProcess.on('close', (code) => {
        console.log(`server.js exited with code ${code}`);
    });

    serverProcess.on('error', (err) => {
        console.error('Failed to start server.js:', err);
    });

    createWindow();
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});

app.on('will-quit', () => {
    if (serverProcess) {
        serverProcess.kill();
    }
});

process.on('uncaughtException', (error) => {
    console.error('Uncaught Exception:', error);
    if (serverProcess) {
        serverProcess.kill();
    }
    app.quit();
});